//
//  SomeProfileIdentifierViewController.m
//  MingShi
//
//  Created by MJiao on 15/7/2.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "SomeProfileIdentifierViewController.h"

#import "UIImageView+AFNetworking.h"
#import "MJRefresh.h"
#import "ImgeUtil.h"
#import "ViewImageScaleViewController.h"
#include "AFHTTPRequestOperationManager.h"
#import "UserManager.h"
#import "SomeProfilePageModel.h"
#import "SomeProfile.h"
#import "SomeProfileTableViewCell.h"
#import "MyAnswerTableViewCell.h"
#import "User.h"
#import "QuestionDetailViewController.h"
#import "Question.h"
#import "CommonUtils.h"
#import "KVNProgress.h"
#import "SomeQuestionTableViewCell.h"

@interface SomeProfileIdentifierViewController ()
@property(strong, nonatomic) SomeProfilePageModel *someProfilePageModel;
@property(nonatomic, strong) Question *didSelectedQuestion;
@end

@implementation SomeProfileIdentifierViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self.contentView setHidden:YES];


    if (!self.someProfilePageModel) {
        self.someProfilePageModel = [[SomeProfilePageModel alloc] init];
        self.someProfilePageModel.dataArray = [[NSMutableArray alloc] init];
    }
    //我关注的
    if (self.following) {

    }
        //关注我的
    else {
        [self.btnFollow setTitle:@"关注" forState:UIControlStateNormal];
    }
    
//    self.viewSchoolBg.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
//    self.viewSchoolBg.layer.borderWidth = 1.0;
//
//    self.viewSchoolBg.layer.cornerRadius = 5;
//    self.viewSchoolBg.layer.masksToBounds = YES;

    

    //添加这两行代码
//    启用估算行高
//    在iOS8上，苹果将许多在iOS8之前比较难实现的东西都内置实现了。
// 为了让cell实现self-sizing的机制，必须先将tableView的rowHeight属性设置为常量UITableViewAutomaticDimension。
// 然后，只需将tableView的estimatedRowHeight属性设置为非零值即可开启行高估算功能
//    self.tableView.estimatedRowHeight = 304.0f;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;


    //圆角
    self.ivAvatar.layer.masksToBounds = YES;
    self.ivAvatar.layer.cornerRadius = 27.5;


    self.scrollView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{


        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

        NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/users/getId?Id=%ld", self.fid];


        NSLog(@"urlString:%@", urlString);
        [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            [self.contentView setHidden:NO];

            // 结束刷新
            [self.scrollView.header endRefreshing];

            id user = [responseObject objectForKey:@"user"];
            NSString *userName = [user objectForKey:@"userName"];
            userName = [CommonUtils serializableIdObject:userName defaultValue:@"昵称"];


            id liginName = [user objectForKey:@"loingName"];
            id slogins = [user objectForKey:@"slogins"];
            id gradeName = [user objectForKey:@"gradeName"];
            id schoolName = [user objectForKey:@"schoolName"];
            id brith = [user objectForKey:@"brith"];
            id imageUrl = [user objectForKey:@"imageUrl"];

            slogins = [CommonUtils serializableIdObject:slogins defaultValue:@"这家伙很懒，连资料都不修改"];
            gradeName = [CommonUtils serializableIdObject:gradeName defaultValue:@" "];
            schoolName = [CommonUtils serializableIdObject:schoolName defaultValue:@" "];
            brith = [CommonUtils serializableIdObject:brith defaultValue:@""];
            imageUrl = [CommonUtils serializableIdObject:imageUrl defaultValue:@""];

             if(imageUrl ){
                 [self.ivAvatar setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
             }


            [self.lbNickName setText:userName];
            [self.lbGradeValue setText:gradeName];
            [self.lbSchoolValue setText:schoolName];
            [self.lbAgeValue setText:brith];


            [self.lvSign setText:slogins];

            id help = [responseObject objectForKey:@"help"];
            NSMutableArray *dataArray = [[NSMutableArray alloc] init];
            self.someProfilePageModel.dataArray = dataArray;

            NSInteger allCount = [[help objectForKey:@"allCount"] integerValue];
            [self.lvHelpCount setText:[NSString stringWithFormat:@"（%ld）", allCount]];

            /**
            * 解析他回答问题列表
            */
            NSArray *result = [help objectForKey:@"result"];
            [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                SomeProfile *someProfile = [[SomeProfile alloc] init];
                someProfile.contents = [obj objectForKey:@"contents"];
                someProfile.createtime = [obj objectForKey:@"createtime"];
                someProfile.imageUrl = [obj objectForKey:@"imageUrl"];
                someProfile.isopen = [[obj objectForKey:@"isopen"] integerValue];
                someProfile.plnum = [[obj objectForKey:@"plnum"] integerValue];
                someProfile.sex = [obj objectForKey:@"sex"];
                someProfile.slogins = [obj objectForKey:@"slogins"];
                someProfile.someProfileId = [[obj objectForKey:@"id"] integerValue];
                someProfile.status = [obj objectForKey:@"status"];
                someProfile.createtime = [obj objectForKey:@"createtime"];
                someProfile.subjectName = [obj objectForKey:@"subjectName"];
                someProfile.userImage = [obj objectForKey:@"userImage"];
                someProfile.userId = [[obj objectForKey:@"userId"] integerValue];
                someProfile.wenwen = [obj objectForKey:@"wenwen"];
                someProfile.userName = [obj objectForKey:@"userName"];
                someProfile.gradeName = [obj objectForKey:@"gradeName"];

                someProfile.resizedImageUrl = [obj objectForKey:@"resizedImageUrl"];

                someProfile.imageWidth = [[obj objectForKey:@"imageWidth"] integerValue];
                someProfile.imageHeight = [[obj objectForKey:@"imageHeight"] integerValue];
                someProfile.resizedImageWidth = [[obj objectForKey:@"resizedImageWidth"] integerValue];
                someProfile.resizedImageHeight = [[obj objectForKey:@"resizedImageHeight"] integerValue];

                [self.someProfilePageModel.dataArray addObject:someProfile];

            }];
            [self.tableView reloadData];

        }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);

            // 结束刷新
            [self.tableView.header endRefreshing];
        }];


        // 进入刷新状态后会自动调用这个block
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.scrollView.header.autoChangeAlpha = YES;

    // 马上进入刷新状态
    [self.scrollView.header beginRefreshing];


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  //  NSLog(@"[self.someProfilePageModel.dataArray count]:%ld", [self.someProfilePageModel.dataArray count]);
    return [self.someProfilePageModel.dataArray count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    static NSString *ID = @"SomeProfileTableViewCellID";
//    SomeProfileTableViewCell *someProfileTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];
//    if (someProfileTableViewCell == nil) {
//        someProfileTableViewCell = [[SomeProfileTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//    }

    static NSString *ID = @"SomeQuestionTableViewCell";

    SomeQuestionTableViewCell *myAnswerTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (myAnswerTableViewCell == nil) {
        myAnswerTableViewCell = [[SomeQuestionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        //将Custom.xib中的所有对象载入
//        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SomeQuestionTableViewCell" owner:nil options:nil];
//        //第一个对象就是CustomCell了
//        myAnswerTableViewCell = [nib objectAtIndex:0];
    }



    SomeProfile *someProfile = [self.someProfilePageModel.dataArray objectAtIndex:[indexPath row]];
//
    NSString *status = @"已解决";
    if ([someProfile.status isEqualToString:@"0"]) {
        status = @"待解决";
    } else if ([someProfile.status isEqualToString:@"1"]) {
        status = @"已解决";
    }

    NSString *reply = [NSString stringWithFormat:@"%ld回复", (unsigned long) someProfile.plnum];
    NSString *subjectName = [CommonUtils serializableIdObject:someProfile.subjectName defaultValue:@""];
    NSString *gradeName = [CommonUtils serializableIdObject:someProfile.gradeName defaultValue:@""];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    //"createtime": "2015-07-09 17:32:43",
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];

    NSString *createTime = someProfile.createtime;
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:someProfile.createtime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }

    [myAnswerTableViewCell.lbStatus setText:status];
    [myAnswerTableViewCell.lbContents setText:someProfile.contents];
    [myAnswerTableViewCell.lbPostTime setText:createTime];
    [myAnswerTableViewCell.lbSubjectName setText:subjectName];
    [myAnswerTableViewCell.lbGradeName setText:gradeName];
    [myAnswerTableViewCell.lbReplyCount setText:reply];
    [myAnswerTableViewCell.lbGradeName setText:gradeName];
    return myAnswerTableViewCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SomeProfile *someProfile = self.someProfilePageModel.dataArray[indexPath.row];

    Question *question = [[Question alloc] init];
    question.answerId = someProfile.someProfileId;
    question.contents = someProfile.contents;
    question.createTime = someProfile.createtime;
    question.gradeName = someProfile.gradeName;
    question.subjectName = someProfile.subjectName;
    question.questionId = someProfile.someProfileId;
    question.sex = someProfile.sex;
    question.imageUrl = someProfile.imageUrl;
    question.resizedImageUrl = someProfile.resizedImageUrl;
    question.imageHeight = someProfile.imageHeight;
    question.imageWidth = someProfile.imageWidth;
    question.resizedImageHeight = someProfile.resizedImageHeight;
    question.resizedImageWidth = someProfile.resizedImageWidth;

    question.userImage = someProfile.userImage;

    question.slogins = someProfile.slogins;
    question.status = someProfile.status;
    question.userName = someProfile.userName;

    self.didSelectedQuestion = question;

    [self performSegueWithIdentifier:@"QuestionDetailSegueIdentifer" sender:self];
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([sender isKindOfClass:[MyAnswerTableViewCell class]]) {
        // prevent segue from occurring
        return NO;
    }
    // by default perform the segue transition
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"QuestionDetailSegueIdentifer"]) {
        QuestionDetailViewController *destination = segue.destinationViewController;
        [destination setQuestion:self.didSelectedQuestion];
    }
}


//tableView:estimatedHeightForRowAtIndexPath
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return UITableViewAutomaticDimension;
//}
//
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return UITableViewAutomaticDimension;
//}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnCancelFellow:(id)sender {

    //我关注的
    if (self.following) {
        [self processCancelFellowing:sender];
    }
        //关注我的
    else {
        [self processGoFellowing:sender];
    }


}

- (void)processGoFellowing:(id)sender {
    //登录成功后进行第二步

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    [KVNProgress showWithStatus:@"正在关注,请稍后..."];

    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/payAttent?userId=%ld&fid=%ld", [[UserManager shareUserManager] curUser].userId, (unsigned long) self.fid];

    // NSLog(@"urlString:%@",urlString);

    [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [KVNProgress dismiss];
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"00"]) {
            [sender setHidden:YES];
            [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"]];
        } else {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
        }
    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];

    }];
}

- (void)processCancelFellowing:(id)sender {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    [KVNProgress showWithStatus:@"正在取消关注,请稍后..."];
    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/cancelAttent?userId=%ld&fid=%ld", [[UserManager shareUserManager] curUser].userId, (unsigned long) self.fid];

    //NSLog(@"urlString:%@",urlString);

    [manager POST:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [KVNProgress dismiss];
        NSString *code = [responseObject objectForKey:@"code"];
        if ([code isEqualToString:@"00"]) {
            [sender setHidden:YES];
            [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"] completion:^{
                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                [userInfo setObject:@"refreshData" forKey:@"refreshData"];

                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:@"SecVCPopped" object:self userInfo:userInfo];

                // Things you want to do after the HUD is gone.
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        } else {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
        }
    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];

    }];
}
@end
